package com.dubito.exif;

import com.drew.imaging.ImageProcessingException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.lang.GeoLocation;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.GpsDirectory;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

/**
 * @author liliang
 * @description:
 * @date 2019/2/17.
 */
public class ExifJpg {

    public static void main(String[] args) throws ImageProcessingException,
            IOException, MetadataException {
        File jpegFile = new File("/Users/liliang/Desktop/1461550333246_.pic_hd.jpg");
        Metadata meta = JpegMetadataReader.readMetadata(jpegFile);
        Iterable<Directory> directories = meta.getDirectories();
        for (Directory directory : directories) {
            Collection<Tag> tags = directory.getTags();
            for (Tag tag : tags) {
                System.out.println(tag);
            }
        }

        readExifLatitudeAndLongitude("/Users/liliang/Desktop/17901550327844_.pic_hd.jpg");
    }

    /**
     * 获取图片的地理位置
     *
     * @param filePath 图片路径
     */
    public static void readExifLatitudeAndLongitude(String filePath) {
        try {
            Metadata meta = JpegMetadataReader.readMetadata(new File(filePath));
            Collection<GpsDirectory> gps = meta.getDirectoriesOfType(GpsDirectory.class);
            for (GpsDirectory gp : gps) {
                GeoLocation geoLocation = gp.getGeoLocation();
                double latitude = geoLocation.getLatitude();
                double longitude = geoLocation.getLongitude();
                System.out.println(latitude);
                System.out.println(longitude);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
